1
1
101002016-02-20 20:45:54
ruby
10100, 2016-02-20 20:45:54

How to make the form see comments?

I can't even really compose a question for a google search. I know there should be a thread like this but I can't find it to watch.
Basically I have: Controller: Posts
Models: Post , Comment
The Post model has a one-to-many relationship with the Comment
model Example:

class Post < ActiveRecord::Base

  has_many :comments

end

class Comment < ActiveRecord::Base

  belongs_to :post

end

The migration looks like this:
class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.integer :user_id
      t.text    :text
      t.timestamps
    end
  end
end

I have a View for the Post controller, it's called show.html.erb In it, I can easily display the titles of articles like this:
<%= @post.name %>
The problem is that on the same page, at the very bottom, I want to add a form for creating a comment, but I can't This can be achieved because when you try to write something like this:
<%= form_for @comments do |f| %>
<%= f.text_field :text %>
<% end %>

show.html.erb page gives #=> error
undefined method `model_name' for Comment::ActiveRecord_Relation:Class

It seems somehow possible to force the view of one controller to see the values ​​​​of another controller in itself. In general, please tell me how to do it right or where I stumbled.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey P, 2016-02-20
@ruddy22

Hope this helps
Read more here
rusrails.ru/rails-form-helpers#sozdanie-slozhnyh-form

class Person < ActiveRecord::Base
  has_many :addresses
  accepts_nested_attributes_for :addresses
 
end
 
class Address < ActiveRecord::Base
  belongs_to :person
end

<%= form_for @person do |f| %>
  Addresses:
  <ul>
    <%= f.fields_for :addresses do |addresses_form| %>
      <li>
        <%= addresses_form.label :kind %>
        <%= addresses_form.text_field :kind %>
 
        <%= addresses_form.label :street %>
        <%= addresses_form.text_field :street %>
        ...
      </li>
    <% end %>
  </ul>
<% end %>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question