0

I'm trying to setup the following: A User has many Groups through Memberships, a Group has many Events, and an Event has many Posts.

On my view to show a group with all of its events, I want a user to be able to write a new post by selecting the correct group from a drop down, writing a comment and submit. I'm currently using a collection_select to create the post, but the event_id is not getting passed to ActiveRecord, i.e. posts are created, but they do not have event_ids (or even comments):

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%>

I have a feeling that because the routes are nested, group_id never is passed to the Posts controller, and so can never be set. But I'm sure there's a lot more wrong than that...

4

1 回答 1

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 %>
于 2014-03-25T17:37:36.747 回答