我有两个模型,字符和背景。字符有_one 背景,背景属于_to 字符。我有一个 _menu 部分设置显示在我的角色视图中,以允许用户查看与角色相关的其他模型,例如项目和法术。
但是,Character 与这些其他模型具有 has_many 关系,我无法弄清楚如何正确链接到具有 has_one 关系的模型。
对于 has_many 模型,这是从我的 Character 视图页面添加新页面的方法:
<%= link_to 'Items Page', character_items_path(@character) unless @character.items.exists? %>
这是菜单部分的代码,一旦创建页面,它将链接到页面:
<%= link_to 'Items', character_items_path(@character) if @character.items.exists? %>
以及来自我的背景控制器的代码:
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 'Background', character_background_path(@character) if @character.background.exists? %>
但随后 Rails 抱怨 .exists?是一个未定义的方法。我猜 .exists 不适用于 has_one 关系,否则我一开始就错误地使用它。感谢您的任何意见!