【问题标题】:Create and update two models with a join model (has_many through) and extra fields使用连接模型(has_many through)和额外字段创建和更新两个模型
【发布时间】:2011-03-01 22:06:40
【问题描述】:

我一直在尝试通过简单地将我的两个主要列(属性和用户)通过连接模型(演员)链接到我有两个 ID(property_id 和 user_id)和一个字符串列(角色),我将为其添加纯文本。但是,我什至不知道如何在视图中为这个简单的模型做一个简单的创建;我已经阅读了几十个关于 has_many :through 和额外字段的线程,但仍然不知道如何做到这一点......有人对如何实现这个有一个简单的答案吗?看来,如果我使用 .net,我会在大约 2 周前完成......

【问题讨论】:

    标签: ruby-on-rails has-many-through


    【解决方案1】:
    class User < ActiveRecord::Base
      has_many :properties, :through => :actorships
      has_many :actorships
    end
    
    class Property < ActiveRecord::Base
      has_many :users, :through => :actorships
      has_many :actorships
    end
    
    class Actorship < ActiveRecord::Base
      belongs_to :user
      belongs_to :property
    end
    
    user = User.last
    new_actorship = user.actorships.create(:property=>Property.last, :role => 'omg')
    # => Actorship associated to User and Property, with role 'omg'
    
    user.properties
    # => [Property.last]
    

    【讨论】:

    • 我假设这是在控制器中。您如何动态获取“omg”(即从视图内的 collection_select)?
    • 我在参数中有这些,但似乎无法访问散列中的特定符号。我可以将 current_user.id 用于 :user_id,但我不知道如何处理该角色。这不起作用: new_actorship = @property.actorships.create(:user_id=>current_user.id, :role => params[:property][:actorship_attributes].role) (也不是 params[:property][:actorship_attributes] );它返回 nul 或类似 '--- :role\n' 或哈希本身。
    • 我不知道角色是什么。它是一个字符串值吗?它是与另一个对象的关联吗?
    • 这行得通:new_actorship = @property.actorships.create(params[:property][:actorship_attributes])
    • 给你。我不知道我必须接受答案并投票(我在这里(和 RoR)相当新)。
    猜你喜欢
    • 2016-02-15
    • 2012-05-16
    • 2011-02-16
    • 1970-01-01
    • 2012-02-28
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多