I have one model "Breads" that has_many "Posts". I would like to have a form to create a new "Post" on the 'show' page for a given "Bread" that creates the association to the record of 'Bread' which the 'show' page is displaying.
I have tried a few different methods, but all are giving an error. The method that I have shown below gives a "Association cannot be used in forms not associated with an object" error.
/views/breads/show.html.erb:
<p>
<strong>Bread Type:</strong>
<%= @bread.bread_type %>
</p>
<table>
<tr>
<th>Uploaded By</th>
<th>Comment</th>
<th>Picture</th>
</tr>
<% @bread.posts.each do |post| %>
<tr>
<td><%= post.uploader %></td>
<td><%= post.comment %></td>
<td><%= image_tag post.attachment_url.to_s %></td>
</tr>
<% end %>
</table>
<%= @bread.id %>
<%= simple_form_for @bread do |b| %>
<%= simple_fields_for :posts do |p| %>
<%= p.input :uploader %>
<%= p.input :comment %>
<%= p.association :bread, value: @bread.id %>
<%= p.file_field :attachment %><br>
<%= p.button :submit %>
<% end %>
<% end %>
<%= link_to 'Back', breads_path %>
config/routes.rb
Rails.application.routes.draw do
get 'welcome/index'
root 'welcome#index'
resources :breads
resources :posts
end
controllers/breads_controller.rb:
class BreadsController < ApplicationController
def index
@breads = Bread.all
end
def show
@bread = Bread.find(params[:id])
end
def new
@bread = Bread.new
end
def edit
@bread = Bread.find(params[:id])
end
def create
@bread = Bread.new(bread_params)
if @bread.save
redirect_to @bread
else
render 'new'
end
end
def update
@bread = Bread.find(params[:id])
if @bread.update(bread_params)
redirect_to @bread
else
render 'edit'
end
end
def destroy
@bread = Bread.find(params[:id])
@bread.destroy
redirect_to breads_path
end
private
def bread_params
params.require(:bread).permit(:bread_type)
end
end
Aucun commentaire:
Enregistrer un commentaire