【问题标题】:Attribute not being set未设置属性
【发布时间】:2011-03-27 22:18:10
【问题描述】:

我的用户 new 表单中有这个用于单选按钮的 ruby​​ 代码:

<%= f.fields_for :profile, Profile.new do |t| %>
 <div class ="field">
    <%= t.label :type, "Are you an artist or listener?" %><br />
    <p> Artist: <%= t.radio_button :type, "artist" %></p>
    <p> Listener: <%= t.radio_button :type, "listener" %></p>
  </div>
<% end %>    

我想设置我的 Profile 模型的 type 属性。但是,类型未设置,默认为nil。我尝试在我的配置文件控制器中创建此 create 方法,但它不起作用:

def create
  @profile = Profile.find(params[:id])
  if params[:profile_attributes][:type] == "artist"
    @profile.type = "artist"
  elsif params[:profile_attributes][:type] == "listener"
    @profile.type = "listener"
  end
end

如何将type 正确设置为“艺术家”或“听众”?

更新:

我收到此错误:WARNING: Can't mass-assign protected attributes: type

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3


    【解决方案1】:

    我想你想这样访问它:

    params[:user][:profile_attributes][:type]
    

    您的视图应该类似于:

    <%= form_for(setup_user(@user)) do |f| %>
      <p>
        <%= f.label :email %>
        <br/>
        <%= f.text_field :email %>
      </p>
      <%= f.fields_for :profile do |profile| %>
        <%= profile.label :username %>
        <br/>
        <%= profile.text_field :username %>
    

    在你的 helpers/application_helper.rb 中

      def setup_user(user)
        user.tap do |u|
          u.build_profile if u.profile.nil?
        end
      end
    

    这只是一个例子。

    【讨论】:

    • 谢谢,但我似乎仍然无法设置type...你能告诉我我应该使用的表单代码和控制器代码吗...我一定得到了什么错了
    • 设置type的控制器代码呢?由于某种原因仍然无法设置...
    【解决方案2】:

    我的第一个答案很糟糕:

    确保您的类型字符串是 CamelCased。另外,我相信类型是 attr_protected 意味着你不能通过 attr_accesible 设置它。

    这样的事情可能会让你朝着正确的方向前进:

    class ProfilesController < ApplicationController
      def create
        @profile = profile_type.new(pararms[:profile])
        if @profile.save(params[:profile])
          # ...
        else
          # ...
        end
      end
    
    private
    
      def profile_type
        params[:profile][:type].classify.constantize if %w(Artist Listener).include? params[:profile][type]
      end
    
    end
    

    【讨论】:

    • 正确的类型。将属性 type 重命名为 profile_type 将绕过这个问题。 type 属性用于单表继承 (STI),不应在模型中创建属性时使用。有关详细信息,请参阅文档中的“单表继承”部分api.rubyonrails.org/classes/ActiveRecord/Base.html
    【解决方案3】:

    试试这个功能:

       <%= f.fields_for :profile, @user.build_profile(:type => "Artist") do |t| %>
    

    【讨论】:

    • 那么我也可以摆脱before_create :build_profile 回调吗?
    • 我应该将类型自动设置为艺术家?这似乎不起作用..
    • 大写?字符串,对吧?另外,我可以摆脱那个控制器代码吗?仍然无法获取type 设置:/
    • 我相信 type 在 rails 3 中是 attr_protected,这意味着 :type => 'ClassName' 将不起作用。
    猜你喜欢
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多