Okay, so I am currently working on a commenting system where posts belong to classrooms and posts have comments. So classrooms have comments through posts.
Here are the models
class Classroom < ActiveRecord::Base
has_many :posts
has_many :comments, through: :posts
...
end
class Comment < ActiveRecord::Base
belongs_to :post
...
end
class Post < ActiveRecord::Base
belongs_to :classroom
has_many :comments
...
end
I'm trying to save post_ids but it won't let me with a simple hidden field so I tried it with a value and it still doesn't work. it says that post_id is an undefined method.
Here is my classroom controller's show method because it is where the new comment form is being rendered.
def show
@classroom = Classroom.find(params[:id])
@posts = @classroom.posts
@comments = @classroom.comments
@comment = Comment.new
end
Here is the new comment form.
<%= simple_form_for(@comment) do |f| %>
<%= f.error_notification %>
<%= f.text_area :content %>
<%= f.hidden_field :post_id, :value => @classroom.post_id %>
<div class="form-actions">
<br>
<%= f.button :submit %>
</div>
<% end %>
Error Message NoMethodError in Classrooms#show undefined method `post_id' for Classroom:0x007f52aa646b18
How do I save the post_id? Thanks!
NoMethodError in Classrooms#show undefined method `post_id' for Classroom:0x007f52aa646b18
<%= f.hidden_field :post_id, :value => @classroom.post_id %>
The error is obvious as you are doing @classroom.post_id
as Classroom
don't have a field called post_id
Define a @post
with the help of @classroom
def show
@classroom = Classroom.find(params[:id])
@post = Post.where(classroom_id: @classroom.id).first
@posts = @classroom.posts
@comments = @classroom.comments
@comment = Comment.new
end
and use that in the hidden_field
<%= f.hidden_field :post_id, :value => @post.id %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.