开发者

In Rails, how can one move a "new" view for one model to a "show" view from another model?

开发者 https://www.devze.com 2023-01-13 06:08 出处:网络
I\'ve been reading and watching videos on nested forms, but I hav开发者_如何学Pythonen\'t had any luck getting things working. (...and I know this just has to be incredibly easy...)

I've been reading and watching videos on nested forms, but I hav开发者_如何学Pythonen't had any luck getting things working. (...and I know this just has to be incredibly easy...)

I have this view 'views/comments/new':

<% form_for([@job, @comment]) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :body %><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.submit "Create" %>
</p>
<% end %>

...and I would like to move this form/text box to the 'jobs/show' view.

my job model: job.rb

belongs_to :user
has_many :comments, :dependent => :destroy
has_many :assets
accepts_nested_attributes_for :assets
accepts_nested_attributes_for :comments

What I would like to do is have the form to add new comments at the bottom of the this job "show" page. Instead of going to "/jobs/15/comments/new", I would like to have the "new comment" form in the jobs show view.

How could I do this?

Cheers.


You can drop that form code in comments/new right into the jobs/show view, but you need to make sure you define @comment in your controller.

jobs_controller.rb

def show
 @job = Job.find(params[:id])
 @comment = @job.comments.new
respond_to do |format|
 format.html
end
end

You'll probably want to make sure that the create action for comments redirects users back to the job, not the comment.

My personal recommendation would be to move that form to a partial, but if you're just getting started with rails this will get you going in the right direction.


If I got it right, you want to show all comments for a job in the job show page, right?

If that's the case, I think the following code will do the job:

<% @job.comments.each do |comment| -%>
  <%= comment.body %>
  <p/>
<% end -%>
0

精彩评论

暂无评论...
验证码 换一张
取 消