質問

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

役に立ちましたか?

解決

can you try to pass Post.create(post_params) instead of Post.create(params[post_params])

post_params is actually a full hash extracted from the params so you should not pass it to params again

If you want to add user_id you should add to your view something like this

 <%= f.hidden_field :user_id, value: current_user.id %>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top