0

There is a cool feature for has_many in Rails. I can write

class Article < AR::Base
  has_many :comments
  has_one  :another_association

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 has_one, like @article.another_association_id = 1. But I get NoMethodError exception. Is there any way to make this method works?

asiniy
  • 13,006
  • 7
  • 59
  • 135

4 Answers4

1

Has one has a different syntax.

@article.build_another_association
@article.create_another_association

See the guides for more info

j-dexx
  • 10,138
  • 3
  • 21
  • 35
0

Use attr_accessible

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.

Community
  • 1
  • 1
Mike S
  • 11,081
  • 6
  • 38
  • 73
0

You have the direction of the association reversed.

  • With has_one, the other class should have an article_id to refer to a record in your articles table.
  • If you want articles.another_association_id, then you should specify belongs_to :another_association.

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.

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one

Alex
  • 228
  • 1
  • 8
  • I think the OP mistakenly wrote his example backwards because the same thing should be true for his `has_many` example. But he claims that `@article.comment_ids = [1,2,3]` works. Even though that would also require `belongs_to :comment`. – Mike S Nov 25 '15 at 17:22
0

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
charlysisto
  • 3,680
  • 16
  • 30