There is a cool feature for
has_many in Rails. I can write
class Article < AR::Base
and voila! method
comment_ids= created, which I can use in strong parameters and mass assignment. Somethind like
@article.comment_ids = [1,2,3]
I need something similar for
@article.another_association_id = 1. But I get
NoMethodError exception. Is there any way to make this method works?
Has one has a different syntax.
See the guides for more info
Specifies a white list of model attributes that can be set via mass-assignment
So you can add it like this assuming you created and ran the migration already:
class Article < AR::Base has_many :comments has_one :another_association attr_accessible :another_association_id
But if it's Rails 4 you may need to handle it in the controller.
You have the direction of the association reversed.
has_one, the other class should have an
article_idto refer to a record in your
articles.another_association_id, then you should specify
This method should only be used if the other class contains the foreign key. If the current class contains the foreign key, then you should use belongs_to instead.
If you want to simulate the way
has_many works you could try this:
class Article < AR::Base has_one :page def page_id=(int_id) self.page = Page.find(int_id) end end @article.page_id = 3