Reputation: 33755
So I have a Node
, Video
, FamilyTree
and User
.
When you are logged in as a current_user
, they can upload a video. Whenever a video
is uploaded, it becomes a node
on the current_user's family_tree
.
The main association is: Video has_one Node
.
This works:
@video.create_node(name: @video.title, family_tree_id: @family_tree.id, user_id: current_user.id)
However, per the Rails Guides, I should be able to do something like this:
@video.create_node(@family_tree.attributes)
That doesn't exactly work, because it assigns the family_tree.name
to node.name
which is not correct (as you can see from my correct example above).
I tried something like this:
@video.create_node(@video.attributes, @family_tree.attributes, current_user.attributes)
But that didn't work.
How do I do this in a more elegant Rails way?
Upvotes: 0
Views: 28
Reputation: 34072
Apart from passing associations by name and not key (user
vs user_id
, etc), this is already about as railsy as you get.
Rails has its share of magic but I don't think there's anything about creating one record out of the attributes of another as in your example.
End result would look something like:
@video.create_node(
name: @video.title,
family_tree: @family_tree,
user: current_user
)
Upvotes: 2
Reputation: 1124
@numbers... is correct, you have to name the specific attributes in order for rails to know which attributes you mean. So your first example is correct, the second is flawed.
However there is another option, you can create another method called (for example) create_node_on_video, accept both of the models video and family-tree and within this helper method method pick out and save the elements needed using create_node.
def create_node_on_video
return if @video.nil? or @family-tree.nil?
@video.create_node(name: @video.title, family_tree_id: @family_tree.id, user_id: current_user.id)
end
Upvotes: 1