我试图设置以下内容:用户有许多组通过成员身份,组有许多事件,并且事件有许多帖子。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控制器,所以永远不能设置。但我敢肯定有很多比这更错误的...
注:我最终会想补充CURRENT_USER身份证的帖子以及,但我想我会开始得到event_id和评论通过第一 – kyle
你可以尝试通过Post.create(post_params),而不是Post.create(params [post_params]) –
太棒了!这工作,谢谢!你能帮我理解有什么不同吗? – kyle