2014-03-25 47 views
0

我試圖設置以下內容:用戶有許多組通過成員身份,組有許多事件,並且事件有許多帖子。Rails conditional_select爲嵌套屬性

在我看來向所有的事件展示一個組,我希望用戶能夠通過從下拉列表中選擇正確的組寫一個新的帖子,撰寫評論和提交。我目前使用collection_select創造職位,但該事項標識不獲取傳遞給ActiveRecord的,創建即職位,但他們沒有event_ids(甚至評論):

class User < ActiveRecord::Base 
    has_many :memberships 
    has_many :groups, through: :memberships 
    has_many :posts 
end 

class Membership < ActiveRecord::Base 
    belongs_to :group 
    belongs_to :user 
end 

class Group < ActiveRecord::Base 
    has_many :memberships 
    has_many :events, dependent: :destroy 
    has_many :users, through: :memberships 
end 

class Event < ActiveRecord::Base 
    belongs_to :group 
    has_many :posts 
end 

class Post < ActiveRecord::Base 
    belongs_to :event 
    belongs_to :user 
end 



class GroupsController < ApplicationController 
    def show 
    #define new post 
    @new_post = Post.new 
    end 
end 


class PostsController < ApplicationController 
    def create 
    if @post = Post.create(params[post_params]) 
     flash[:success] = "Post Created!" 
    else 
     redirect_to group_url 
    end 
    end 

    private 
    def post_params 
     params.require(:post).permit(:event_id, :comment) 
    end 
end 


<h1>New Post:</h1> 
<%=form_for([@new_post]) do |f| %> 
<%= render 'shared/error_messages', object: f.object %> 
    <div class = "field"> 
     <%= f.label :event_name %> 
     <%= f.collection_select(:event_id, Event.all, :id, :title) %> 
    </div> 
    <div class = "field"> 
     <%= f.text_area :comment, placeholder: "New Post..." %> 
    </div> 
    <%=f.submit "Submit", class: "btn btn-large btn-primary" %> 
<%end%> 

我有一種感覺因爲路由是嵌套的,所以group_id永遠不會傳遞給Posts控制器,所以永遠不能設置。但我敢肯定有很多比這更錯誤的...

+0

注:我最終會想補充CURRENT_USER身份證的帖子以及,但我想我會開始得到event_id和評論通過第一 – kyle

+1

你可以嘗試通過Post.create(post_params),而不是Post.create(params [post_params]) –

+0

太棒了!這工作,謝謝!你能幫我理解有什麼不同嗎? – kyle

回答

1

,你可以嘗試通過Post.create(post_params),而不是Post.create(PARAMS [post_params])

post_params實際上是一個完整的從params哈希表中提取,所以你不應該再把它傳給PARAMS

如果你想添加USER_ID 你應該添加到您的看法是這樣的

<%= f.hidden_field :user_id, value: current_user.id %> 
+0

謝謝,那就是訣竅!任何關於添加user_id以及通過隱藏字段的想法? – kyle

+0

現在只需在一秒內添加它 –

+0

user_id現在工作得很好。謝謝! – kyle