Rails - Routing Error - Calling a model from another model -
question: goal list projects under user's page, , have comment box render under each project listed on user page. when try render comment box form, routing error. know because not being able pull out id of project. guess controller have not figured out. know how can solve this?
routing error no route matches {:controller=>"comments", :format=>nil, :project_id=>#<project id: nil...>}
for application, have created models , controllers users, projects, , comments. comments belong projects , projects belong users
user.rb
has_many :projects
project.rb
has_many :comments belongs_to :user
comment.rb
belongs_to :project
routes.rb
resources :users resources :projects resources :comments end end resources :projects resources :comments end resources: comments
view/users/projects.html.erb
<%= render @projects %>
view/projects/_project.html.erb
<%= project.content %> <%= render 'comments/form' %>
view/comments/_form.html.erb
<%= form_for([@project, @project.comments.build]) |f| %> <div class="field"> <%= f.text_area :content, :class => "span12", :rows => "3" %> </div> <%= f.hidden_field :user_id, :value => current_user.id %> <div class="actions"> <%= f.submit "add comment", :class => "btn btn-header" %> </div> <% end %>
comments_controller.rb
def create @project = project.find(params[:project_id]) @comment = @project.comments.create!(params[:comment]) if @comment.save redirect_to projects_user_path(@project.user) end end
error redirect above
nomethoderror in commentscontroller#create undefined method `user'
try this:
view/projects/_project.html.erb
<%= project.content %> <%= render 'comments/form', project: project %>
view/comments/_form.html.erb
<%= form_for([project, project.comments.build]) |f| %> ...
you have pass project form partial.
hope helps!
Comments
Post a Comment