Rails: Creating a has_one model in the view of the parent model?
-
27-10-2019 - |
سؤال
I have two models, Character and Background. Character has_one Background, and Background belongs_to Character. I have a _menu partial set up to display in my Character view, to allow users to view other models related to Character, such as Items and Spells.
However, Character has a has_many relationship with these other models and I'm having trouble figuring out how to link correctly to a model with a has_one relationship.
Here's the method for adding a new page from my Character view page, for a has_many model:
<%= link_to 'Items Page', character_items_path(@character) unless @character.items.exists? %>
And here's the code from the menu partial, that will link to a page once a page has been created:
<%= link_to 'Items', character_items_path(@character) if @character.items.exists? %>
And the code from my Backgrounds controller:
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
Any advice? Basically, I want to have a link_to create a new Background page in the Character show page, then have that Background show up in the Menu partial once it's created and able to be viewed and edited when a user clicks on the link.
I did try writing the code like so:
<%= link_to 'Background', character_background_path(@character) if @character.background.exists? %>
But then Rails complains that .exists? is an undefined method. I'm guessing .exists doesn't work for a has_one relationship, or else I'm using it incorrectly in the first place. Thanks for any input!
المحلول
you should try if @character.background
. This returns nil if no background is found (see http://guides.rubyonrails.org/association_basics.html#has_one-association-reference)