Installation work act_as_commentable, On create, error: "unknown attribute: book_id"

I am working on installing the act_as_commentable plugin on my Rails 3 application.

After adding the book "act_as_commentable" to my model, I added a comment form on my book view page:

<% form_for(@comment) do|f| %> 
  <%= f.hidden_field :book_id %> 
  <%= f.label :comment %><br /> 
  <%= f.text_area :comment %> 
  <%= f.submit "Post Comment" %> 
<% end %> 

Then in the controller (comments_controller.rb),

  def create 
    @comment = Comment.new(params[:comment]) 
    Book.comments.create(:title => "First comment.", :comment => "This 
is the first comment.") 
  end 

Then, sending a comment, it returns an error: "unknown attribute: book_id" From the log:

  Processing by CommentsController#create as HTML 
  Parameters: {"comment"=>{"comment"=>"WOOOW", "book_id"=>"32"}, 
"commit"=>"Post Comment", 
"authenticity_token"=>"5YbtEMpoQL1e9coAIJBOm0WD55vB2XRZMJa4MMAR1YI=", 
"utf8"=>"✓"} 
Completed   in 11ms 
ActiveRecord::UnknownAttributeError (unknown attribute: book_id): 
  app/controllers/comments_controller.rb:3:in `new' 
  app/controllers/comments_controller.rb:3:in `create' 

Suggestions?

+3
source share
2 answers

I think you have options:

Option 1) View:

<% form_for(@comment) do|f| %> 
  <%= f.hidden_field :commentable_id, :value => @book.id %>
  <%= f.hidden_field :commentable_type, :value => 'Book' %> 
  <%= f.label :comment %><br /> 
  <%= f.text_area :comment %> 
  <%= f.submit "Post Comment" %> 
<% end %> 

Controller:

def create
  @comment = Comment.create(params[:comment])
end

Option 2)

In the controller:

def create
  @book = Book.find(params[:comment][:book_id])
  @comment = @book.comments.create(params[:comment].except([:comment][:book_id]))
end

I have not tested the code, but the idea should be correct

, ( , ...). , , , . , .

map.resources :books, :has_many => :comments
map.resources :magazines, :has_many => :comments

:

before_filter :find_commentable

def find_commentable
  @commentable = Book.find(params[:book_id]) if params[:book_id]
  @commentable = Magazine.find(params[:magazine_id]) if params[:magazine_id]
end

:

<% form_for :comment, [@commentable, @comment] do |f| %>
  <%= f.label :comment %>
  <%= f.text_area :comment %>
  <%= f.submit %>
<% end %>

, create :

def create
  @user.comments.create(params[:comment].merge(:commentable_id => @commentable.id, :commentable_type => @commentable.class.name))
  redirect_to @commentable
end

, ...

+2
<%= f.hidden_field :book_id %> 

, Comment book_id. , (). body ( message) Comment , .

+3

Source: https://habr.com/ru/post/1765891/


All Articles