【问题标题】:Displaying the attributes of another table显示另一个表的属性
【发布时间】:2016-04-16 09:13:30
【问题描述】:

我有两个模型:UserRole。 用户属性是:

name:string
email:string 
admin:boolean 
role_id:integer

角色属性是:

designer:boolean 
developer:boolean

我设置的关联是用户belongs_to 角色和角色has_many 用户。 当用户注册时,我希望他选择他的职位(设计师或开发人员)。但是,当我想显示可供选择的职位(设计师和开发人员)时,我将 role_id 作为整数字段。谁能帮我解决这个问题?

【问题讨论】:

  • 你使用的位:admin:booleandesigner:booleandeveloper:boolean 真的让我的眼睛受伤了。我建议你重新考虑你的设计。

标签: ruby-on-rails ruby ruby-on-rails-4 rails-4-2-1


【解决方案1】:

您要执行的操作称为“Nested Models”。

首先你必须告诉模型允许其他模型这样:

# app/model/user.rb
class User < ActiveRecord::Base
  belongs_to :role
  accepts_nested_attributes_for :role
end

接下来的事情就在你的视野中

#app/views/users/new.html.ham
= simple_form_for @user do |f| 
  = f.input :name
  = f.input :email
  %br
  = f.simple_fields_for :role do |role|
    = role.input :designer
    = role.input :developer
  = f.button :submit, "Send Message", :class => 'btn btn-primary btn-block'

现在最后但最起码你能够接受控制器中的新参数

class UsersController < ApplicationController
  expose(:users){User.all.order(:id)}
  expose(:user, attributes: :user_params)

  def new
    @user = User.new
    @user.role.build
  end

  def create
    if user.save
      flash[:notice] = t(:user_was_successfully_created)
      redirect_to root_path
    else
      render :new
    end
  end

  private
  def user_params
    params.require(:user).permit(
      [
        :email ,
        :name ,
        role_attributes: [
          :designer,
          :developer,
        ]
      ]
    )
  end
end

您可以查看示例应用程序https://github.com/mzaragoza/sample_nestes_forms

我希望这会有所帮助 快乐黑客

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 2020-09-17
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多