Question

I think I need to user :through somewhere in my associations, but im very new to this so any help would be appreciated.

For simplicity, lets say I have 3 models.

Faults
Users
FaultComments

Where

Faults - belong_to :user and has_many :fault_comments
Users - has_many :faults and has_many :fault_comments
FaultComments - belongs_to :fault and belongs_to: user

What i would like to do is the ability to add fault comments from the fault show page, currently I have the below but i cant get it all to work as it should.

routes.rb

devise_for :users do
 get '/users/sign_out' => 'devise/sessions#destroy'
end
resources :faults 
resources :fault_comments

views/faults/show.html.erb

<h3>Add New</h3>
<%= form_for @faultcomment, :url => fault_comments_path(:fault_id => @fault.id, :user_id => current_user.id) do |f| %>
<%= f.text_field :comment %>
<%= f.submit %>
<% end %>

controllers/faults_comments_controller.rb

def create
 @fault = Fault.find(params[:fault_id])
 @faultcomment = @fault.fault_comments.new(params[:faultcomment])
 @faultcomment.user_id = params[:user_id]
 @faultcomment.comment = :comment
 if @faultcomment.save
  redirect_to faults_path
 end
end
Was it helpful?

Solution

First of all, I think you should probably leave the FaultCommentsController like it came, which was probably something like this:

def create
  @fault_comment = FaultComment.new(params[:fault_comment])
  @fault_comment.user = current_user
  if @fault_comment.save
    redirect_to faults_path
  end
end

(As a side note, it would probably be worth your while to learn about CamelCase and snake_case and how to properly translate between the two. The snake_case corollary to FaultComment is fault_comment, not faultcomment. You will certainly run into problems if you don't understand this.)

Your form on views/faults/show.html.erb looks more or less right to me. If you change your controller back to the original, does it work?

Also, change your form like this:

<h3>Add New</h3>
<%= form_for @fault_comment, :url => fault_comments_path do |f| %>
<%= f.text_field :comment %>
<%= f.hidden_field :fault_id, @fault.id %>
<%= f.submit %>
<% end %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top