当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - has_one - how to assign_id?

问题描述:

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?

网友答案:

Has one has a different syntax.

@article.build_another_association
@article.create_another_association

See the guides for more info

网友答案:

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.

网友答案:

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

网友答案:

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: