0

I have two forms that I am using. One for sign_up, using devise for authentication, and the second is for adding user comments. I was noticing that when I went through the signup process, the fields I added for first name and last name were ending up nil in the db. I found a solution where this cleared up the problem:

before_filter :configure_devise_params, if: :devise_controller?
  def configure_devise_params
    devise_parameter_sanitizer.for(:sign_up) do |u|
      u.permit(:first_name, :last_name, :profile_name, :email, :password, :password_confirmation)
    end
  end

But in my second form, I added a user_id column to the table and put it in attr_accessible. It, however, is showing up as nil. I'm very new to rails and I'm not sure if this is a problem similar to the first form or if it something completely different.

All the other solutions I've found online seem to point to attr_accessible, but I think I'm good there. So it must be something else. Where else should I look to troubleshoot this? Has anybody else experienced this?

EDIT:

The second form is for user comments. It looks like this:

<%= simple_form_for(@status, html: {class:"form-horizontal"}) do |f| %>
    <%= f.input :user_id %>
    <%= f.input :content %>

    <div class="form-actions">
      <%= f.button :submit %>
    </div>
<% end %>

The content is being saved, but the user_id is nil. I didn't originally have the user_id in the table- I added that later in a migration:

class AddUserIdToStatuses < ActiveRecord::Migration
  def change
    add_column :statuses, :user_id, :integer
    add_index :statuses, :user_id
    remove_column :statuses, :name
  end
end

Also, I know that attr_accessible is a Rails 3 feature and has been done away with in Rails 4. I added gem 'protected_attributes' to my Gemfile so that I could use this, since I didn't know what the convention was for Rails 4. Would I be better off getting rid of this? If so, is there something I should be doing instead of this to protect certain inputs?

4

2 回答 2

0

经过一番研究,我发现 Rails 4 使用 Strong Parameters gem 处理质量分配,它将用户输入移动到控制器。而不是使用

attr_accessible :first_name, :last_name

在模型中,您可以在应用程序控制器中使用类似

def user_params
    params.require(:user).permit(:first_name, :last_name)
end
于 2013-11-09T22:01:44.480 回答
0

如果您在 Rails 4 中使用 protected_attributes,您可能需要禁用强参数。在 config/application.rb 中:

config.action_controller.permit_all_parameters = true

然后重启你的服务器

于 2013-11-08T22:38:54.813 回答