【发布时间】:2014-03-25 15:21:36
【问题描述】:
我正在尝试设置以下内容:一个用户通过会员资格拥有许多组,一个组有许多事件,一个事件有许多帖子。
在我的视图中显示包含所有事件的组,我希望用户能够通过从下拉列表中选择正确的组、撰写评论并提交来撰写新帖子。我目前正在使用 collection_select 创建帖子,但 event_id 没有传递给 ActiveRecord,即帖子已创建,但它们没有 event_ids(甚至没有 cmets):
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 id 添加到帖子中,但我想我会先获取 event_id 并首先通过评论
-
你可以尝试通过 Post.create(post_params) 而不是 Post.create(params[post_params])
-
太棒了!那行得通,谢谢!你能帮我理解有什么区别吗?
-
在尝试将 user_id 添加到帖子时,我在帖子表单中添加了以下内容: 我收到一个错误:未定义的方法`{:user_id=>1}'
标签: ruby-on-rails nested-attributes collection-select