简体   繁体   English

虚拟属性

[英]virtual attributes

<%= form_for(@membership) do |f| %>
  <%= f.collection_select :user_id, User.all, :id, :email %>
  <%= f.collection_select :role_id, Role.all, :id, :name %>
  <%= f.submit %>
<% end %>

What i'm trying to do is instead of using a select box for users, i want to put a text field for users email.我想要做的不是为用户使用 select 框,而是为用户 email 放置一个文本字段。

<%= form_for(@membership) do |f| %>
  <%= f.text_field :email %>
  <%= f.collection_select :role_id, Role.all, :id, :name %>
  <%= f.submit %>
<% end %>

Membership.rb会员资格.rb

belongs_to :user
belong_to :role

attr_accessor :email
def email
 self.user.email if self.user
end

What i dont know is what to write in controller to make it work and is this attr accessor using thing and email method is ok?我不知道在 controller 中写什么以使其工作,这个 attr 访问器是否使用东西和 email 方法可以吗? Any help is appreciated.任何帮助表示赞赏。

  def create
     @membership = Membership.new(params[:membership])
     if @membership.save
        redirect_to(memberships_url)
      else
       render :action => "new"
  end

I think what you're looking for is a nested form.我认为您正在寻找的是嵌套形式。 On the Model that has the has_x designation you can use accepts_nested_attributes_for .在具有 has_x 名称的 Model 上,您可以使用accept_nested_attributes_for There is also a Railscast explaining it.还有一个Railscast解释它。 This means you have two decent options:这意味着您有两个不错的选择:

  1. Redefine your form to be for the user and use fields_for to add the Membership attributes重新定义您的表单以供用户使用并使用 fields_for 添加成员资格属性
  2. Switch your models around so that a User belongs to a Membership and a Membership has_x User(s)切换您的模型,以便用户属于会员资格和会员资格 has_x 用户

If you want it to update existing users only, you'll have to find the user by email in your create action, since Membership needs a user_id and role_id.如果您希望它仅更新现有用户,则必须在创建操作中通过 email 查找用户,因为 Membership 需要 user_id 和 role_id。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM