Rails最佳实践:在模型中创建关联对象

时间:2012-03-09 18:06:19

标签: ruby-on-rails ruby model-view-controller

我有贝塔3个表:用户(电子邮件,密码),联系人(姓名,电话),关系(user_id,contact_id,级别)。

当用户创建新联系人时,我希望他与之关联。该协会的“友谊”水平为1至3。

我使用表单在我的联系人#create controller中输入关卡。

现在,我有这个很棒的

  def create
    @contact = Contact.new(params[:contact])
    if @contact.save
      #@relation = Relation.new(:user_id => current_user.id, :contact_id => @contact.id, :level => params[:relation])
      #@relation.save
      redirect_to root_url, :notice => "ok!"
    else
      render "new"
    end
  end

我正在考虑将关系创建转移到我的联系模式来做这样的事情:

  after_create { Relation.create(user_id: current_user.id, contact_id: self.id, level: params[:relation]) }

当然,这不起作用,但你明白了。 在模型中它是好的还是我现在可以保留它

欢呼声

3 个答案:

答案 0 :(得分:1)

这样的东西?基本上只需创建与current_user相关联的关系和联系人。

current_user.relations.create(联系方式:Contact.new(params [:contact]),level:params [:relation])

请勿将其移至after_create。如果有什么东西在某个地方创建一个接受用户,联系人和关系的功能。

答案 1 :(得分:1)

我宁愿将它保存在控制器中,因为你拥有它。对于测试(以及可能的其他目的),您可能不希望将用户和联系人紧密联系在一起。我看到它的方式是控制器是将创建逻辑联系在一起的地方,模型中的after_create之类的方法更多的是设置某些参数,而不是创建新的关联,将来你可能不会一定要。

tl; dr - 在控制器中放置这样的东西将两个模型紧密地连接在一起。

答案 2 :(得分:1)

<强> contact.rb

has_one :relation
accepts_nested_attributes_for :relation

<强>关系

belongs_to :contact
belongs_to :user

视图

= for_form @contact do |f|
  = f.fields_for :relation do |r|
    = r.text_field :level
  = f.submit 'create'

控制器新动作

  @contact = Contact.new
  @contact.build_relation # create new relation object for the contact

控制器创建操作

  @contact = Contact.new(params[:contact])
  @contact.relation.user = current_user
  @contact.save
相关问题