使用连接模型(has_many到)和额外字段创建和更新两个模型

问题描述:

我一直在尝试通过简单地将我的两个主要列(简单地说是两个主列)简化我以前的帖子的背景(从大约6小时前:https://*.com/questions/5150031/linking-three-models-through-two-join-models) (属性和用户)通过一个连接模型(actorships)链接,其中我有两个ID(property_id和user_id)和一个字符串列(角色),我会为其添加纯文本。但是,我甚至不知道如何在视图中为这个简单的模型创建一个simle;我读过几十个关于has_many的文章:通过和额外的领域,仍然没有线索怎么做...任何人都有一个简单的答案来实现这个?看来,如果我是使用.NET,我会约2个星期前完成......使用连接模型(has_many到)和额外字段创建和更新两个模型

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] 
+0

我假设这是在控制器中。你如何动态获得'omg'(即从视图内的collection_select)? – macro 2011-03-01 16:34:32

+0

我有这些参数,但似乎无法访问散列内的特定符号。我可以使用user_id的current_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'或散列本身。 – macro 2011-03-01 18:30:42

+0

我不知道角色是什么。它是一个字符串值吗?它是否与另一个对象有关联? – Winfield 2011-03-01 19:23:23