mnort9
mnort9

Reputation: 1820

Displaying data from two models in one view

I have two models with respective controllers and views: Profile and Comment.

The entire view (whole webpage) of my application is in the Profile show.html.erb. On this page, the user should be able to create a comment, which belongs_to a Profile.

How can this be accomplished without having to navigate to the standard /comments/new page?

Edit: After following the rails guide, I implemented:

<%= simple_form_for([@profile, @profile.comment.build], html: {class: "form-inline"}) do |f| %>
  <%= f.error_notification %>

  <%= f.input :description, label: false, placeholder: 'Create an comment', input_html: { class: "span4" } %>
  <%= f.submit 'Submit', class: 'btn btn-small'%>

<% end %>

CommentController

 def create
  @profile = profile.find(params[:profile_id])
  @comment = @profile.comments.create(params[:comment])
  redirect_to profile_path(@profile)

And I'm getting this error:

undefined method `comment' for #<Profile:

Fixed: In the build statement, comments needed to be plural

@profile.comments.build

Upvotes: 0

Views: 1112

Answers (2)

sockmonk
sockmonk

Reputation: 4255

You might consider saving the form and updating the page using AJAX calls and possibly something like Knockout. So in profiles/show.html.erb, make a regular (separate) form just for posting comments. Use jQuery or something like it to post the form via AJAX to /comments, so it goes the create action in your comments controller. Have that controller return a JSON response, that will either be the saved comment, or a hash of error messages that looks something like {:fieldname => 'too long'}.

On the client, parse the json response and either display the saved comment, or display the error message explaining why it couldn't be saved. You can do all this in plain jQuery, but adding something like Knockout will make it all a bit simpler.

Upvotes: 0

reknirt
reknirt

Reputation: 2254

All you need to do is add the comment form code into profile#show. Then in the show action of profile_controller do something like:

def show
 @comment = Comment.new
end

And in the comments controller add:

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

Upvotes: 1

Related Questions