我是Rails的新手,努力獲得我的belongs_to協會的權利。我有一個應用程序,一幅繪畫屬於一位藝術家,一位藝術家可以擁有繪畫。我可以創建和編輯我的繪畫,但是除了通過控制檯之外,我無法編輯或創建藝術家。通過很多谷歌搜索,我覺得我已經轉身了。任何幫助將非常感激!無法在Rails 4中創建或更新belongs_to記錄
這是我的routes.rb文件:
MuseumApp::Application.routes.draw do
resources :paintings
resources :paintings do
resources :artists
resources :museums
end
root 'paintings#index'
end
這裏是我的繪畫控制器
def show
@painting = Painting.find params[:id]
end
def new
@painting = Painting.new
#@artist = Artist.new
end
def create
safe_painting_params = params.require(:painting).permit(:title, :image)
@painting = Painting.new safe_painting_params
if @painting.save
redirect_to @painting
else
render :new
end
end
def destroy
@painting = Painting.find(params[:id])
@painting.destroy
redirect_to action: :index
end
def edit
@painting = Painting.find(params[:id])
end
def update
@painting = Painting.find(params[:id])
if @painting.update_attributes(params[:painting].permit(:title, :image)) #safe_params
redirect_to @painting
else
render :edit
end
end
下面是我的畫的形式查看:
<%= form_for(@painting) do |f| %>
<fieldset>
<legend>painting</legend>
<div>
<%= f.label :title %>
<%= f.text_field :title %>
</div>
<div>
<%= f.label :image %>
<%= f.text_field :image %>
</div>
<%= form_for([@painting,@painting.create_artist]) do |f| %>
<div>
<%= f.label :Artist %>
<%= f.text_field :name %>
</div>
</fieldset>
<%= f.submit %>
<% end %>
<% end %>
藝術家控制器:
class ArtistsController < ApplicationController
def index
@artists = Artist.all
@artists = params[:q] ? Artist.search_for(params[:q]) : Artist.all
end
def show
@artist = Artist.find params[:id]
end
def new
@artist = Artist.new
end
def create
@painting = Painting.find(params[:painting_id])
@artist = @painting.create_artist(artist_params)
redirect_to painting_path(@painting)
end
def destroy
@artist = Artist.find(params[:id])
@Artist.destroy
redirect_to action: :index
end
def edit
@artist = Artist.find(params[:id])
end
def update
@painting = Painting.find(params[:painting_id])
@artist = @artist.update_attributes(artist_params)
redirect_to painting_path(@painting)
end
end
private
def artist_params
params.require(:artist).permit(:name)
end
索引視圖:
<h1> Hello and Welcome to Museum App</h1>
<h3><%= link_to "+ Add To Your Collection", new_painting_artist_path %></h3>
<%= form_tag '/', method: :get do %>
<%= search_field_tag :q, params[:q] %>
<%= submit_tag "Search" %>
<% end %>
<br>
<div id="paintings">
<ul>
<% @paintings.each do |painting| %>
<li><%= link_to painting.title, {action: :show, id:painting.id} %> by <%= painting.artist_name %></li>
<div id = "img">
<br><%= link_to (image_tag painting.image), painting.image %><br>
</div>
<%= link_to "Edit", edit_painting_path(id: painting.id) %>
||
<%= link_to 'Destroy', {action: :destroy, id: painting.id},method: :delete, data: {confirm: 'Are you sure?'} %>
<% end %>
</ul>
</div>
你需要閱讀嵌套屬性 - 你不能只巢巢1表單另一 –
感謝並將繼續谷歌和閱讀Rails指南。這張表格看起來並不正確,但是當我「解除嵌套」時,我發現錯誤的是藝術家沒有標題方法。 – edswartz