1

キャラクターと背景の2つのモデルがあります。キャラクターhas_oneBackground、およびBackgroundbelongs_toCharacter。_menuの部分をキャラクタービューに表示するように設定して、ユーザーがアイテムや呪文など、キャラクターに関連する他のモデルを表示できるようにします。

ただし、Characterにはこれらの他のモデルとhas_manyの関係があり、has_oneの関係を持つモデルに正しくリンクする方法を理解するのに問題があります。

has_manyモデルの場合、キャラクタービューページから新しいページを追加する方法は次のとおりです。

<%= link_to 'Items Page', character_items_path(@character) unless @character.items.exists? %>

メニュー部分のコードは次のとおりです。ページが作成されると、ページにリンクします。

<%= link_to 'Items', character_items_path(@character) if @character.items.exists? %>

そして私のBackgroundsコントローラーからのコード:

def new
  @character = Character.find(params[:character_id])
  @background = @character.build_background(params[:background])
end

def create
  @character = Character.find(params[:character_id])
  @background = @character.create_background(params[:background])
   if @background.save
 redirect_to character_path(@character), :notice => "Background information successfully created!"
   else
 render :action => "new"
 end
end

何かアドバイス?基本的に、link_toでキャラクター表示ページに新しい背景ページを作成し、作成後にその背景をメニュー部分に表示して、ユーザーがリンクをクリックしたときに表示および編集できるようにします。

私は次のようにコードを書いてみました:

<%= link_to 'Background', character_background_path(@character) if @character.background.exists? %>

しかし、Railsは.existsと文句を言いますか?未定義のメソッドです。.existsはhas_one関係では機能しないと思います。そうでない場合は、そもそも.existsを誤って使用しています。ご入力いただきありがとうございます。

4

1 に答える 1

2

試してみてくださいif @character.background。背景が見つからない場合、これはnilを返します(http://guides.rubyonrails.org/association_basics.html#has_one-association-referenceを参照)

于 2011-09-07T10:08:07.603 に答える