簡體   English   中英

設置has_many:通過軌道3上的表單

[英]Setting has_many :through with a form on rails 3

我正在嘗試使用表單為用戶創建用戶角色,

<%= form_for @user do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :username %><br />
    <%= f.text_field :username %>
  </p>
  <p>
    <%= f.label :email, "Email Address" %><br />
    <%= f.text_field :email %>
  </p>
  <p>
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </p>
  <p>
    <%= f.label :password_confirmation, "Confirm Password" %><br />
    <%= f.password_field :password_confirmation %>
  </p>

  <% # f.select :roles, Role.all.map {|r| [r.title]} %>

  <% Role.all.each do |role| %>
    <div>
      <%= check_box_tag :role_ids, role.id, @user.roles.include?(role), :name => 'user[role_ids][]' -%>
      <%= label_tag :role_ids, role.title -%>
    </div>
  <% end -%>

  <p><%= f.submit (@user.new_record? ? "Sign up" : "Update"), :id => :sign_up %></p>
<% end %>

這是我模型中的關聯

class user < ActiveRecord::Base
  has_many :assignments
  has_many :roles, :through => :assignments
end

class assignment < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
end

class role < ActiveRecord::Base
  has_many :assignments
  has_many :users, :through => :assignments
end

通過使用我一開始介紹的表單在用戶和角色之間創建分配的方式是什么?

我在用戶控制器中的創建動作如下所示:

def create
   @user = User.new(params[:user])
    if @user.save
      session[:user_id] = @user.id
      render :action => 'dashboard'
    else
      render :action => 'new'
    end
  end

當我發送表格時,出現錯誤:

UsersController#create中的ActiveRecord :: AssociationTypeMismatch

預期角色(#70331681817580),得到的字符串(#70331650003400)

Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"WHpOW+DmymZ2pWmY9NHSuodf2vjyKdgMNZcc8NvCNa0=",
 "user"=>{"username"=>"ioio",
 "email"=>"ioio@ioio.com",
 "password"=>"[FILTERED]",
 "password_confirmation"=>"[FILTERED]",
 "roles"=>["2"]},   #### <<< ==== This is the checkbox that I selected for this request.
 "commit"=>"Sign up"}

歡迎任何幫助。

使用當前表格並基於:

<%= check_box_tag :role_ids, role.id, @user.roles.include?(role), :name => 'user[role_ids][]' -%>

在提交時,您的參數應該看起來像(注意'role_ids'而不是'roles'):

Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"WHpOW+DmymZ2pWmY9NHSuodf2vjyKdgMNZcc8NvCNa0=",
 "user"=>{"username"=>"ioio",
 "email"=>"ioio@ioio.com",
 "password"=>"[FILTERED]",
 "password_confirmation"=>"[FILTERED]",
 "role_ids"=>["2"]},   #### <<< ==== This is the checkbox that I selected for this request.
 "commit"=>"Sign up"}

如果是這種情況,則必須實例化角色並在控制器中為用戶設置它們:

    def create
      @user = User.new(params[:user])
      roles = Role.find(params[:user][:role_ids]) rescue []
      @user.roles = roles
      if @user.save
        session[:user_id] = @user.id
        render :action => 'dashboard'
      else
        render :action => 'new'
      end
    end

...並類似地:

   def update
     @user = User.where(:username=>params[:id]).first
     roles = Role.find(params[:user][:role_ids]) rescue []
     @user.roles = roles
     if @user.update_attributes(params[:user])
       redirect_to users_url, :notice  => "Successfully updated user."
     else
      render :action => 'edit'
     end
   end

該錯誤消息為您提供了提示:為了能夠保存用戶對象,您首先需要以某種方式創建關聯的Role對象。 目前,您只有一個包含角色ID的字符串數組。

您需要在用戶模型上使用accepts_nested_attributes_for方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM