如何保存到数据库在轨质量保护协会assigment [英] How to save to Database with associations in rails protecting mass assigment

查看:147
本文介绍了如何保存到数据库在轨质量保护协会assigment的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试了几个小时后,我无法保存到数据库中。

After trying for few hours I can not save to the database.

的上下文是这样的:
我有两种类型的用户,一个是,我只需要最基本的信息[用户名,电子邮件,密码]和另一种用户对谁,我需要很多的信息[年龄,性别,城市等]

The context is this: I have two types of users, one for that I only need very basic information [Username, email, password] and another kind of user for who I need a lot of information [age, gender, city and so on]

我没有使用STI becouse Null值的大量的事情就在表中。
所以,我创建了一个用户都有一个配置文件(配置文件表)或不取决于它的类型这三种模式[1或2],此配置文件的一个领域是该用户是居住在城市,涉及到另一个表数据库,城市台

I did not use STI becouse of the vast quantity of Null values there would be in the table. So I created this three modes in which a user has a profile (profiles table) or not depending of its type [1 or 2], and a field of this profile is the city this user is living in, that relates to another table in the DB, the cities table

class User < ActiveRecord::Base
  has_one :profile
  has_one :city, through: :profile
end

class Profile < ActiveRecord::Base
  belongs_to :user
  belongs_to :city
  [...a bunch of fields here]
end

class City < ActiveRecord::Base
  has_many :profiles
  has_many :users, through: :profiles
end

当我在钢轨和他们一起玩安慰一切都OK:

When I play with them in the rails console everything goes OK:

usr = User.new(name: "roxy", email: "roxy@example.me", password: "roxanna", password_confirmation: "roxanna", utype: 1)
cty = City.new(name: "Bucaramanga")
prf = Profile.new (rname: "Rosa Juliana Diaz del Castillo"...)
prf.city = cty
usr.profile = prf
usr.valid?
=> true
usr.save
=> true

但是当我尝试在应用程序中保存(查看模型)

but when I try to save in the app (View an Model)

<%= f.label :city, "En que ciudad te encuentras?"%>
<%= select_tag :city, options_from_collection_for_select(City.all, 'id', "name"),{:prompt => 'Selecciona tu ciudad'}%>

def new
  @profile = Profile.new
end

def create
  @profile = params[:profile]
  @city= City.find_by_id(params[:city].to_i)
  @profile.city = @city
end

我得到这个错误:

I get this error:

undefined method `city=' for #<ActiveSupport::HashWithIndifferentAccess:0xa556fe0>

有人能帮帮我吗?

Can someone please help me?

更新
大卫建议我创建的创建方法的第一行Profile对象,所以我现在控制器是这样的:

UPDATE As David suggested I created the Profile object in the first line of the create method, so my controller now look like this:

def create
  @profile = Profile.new(params[:profile])
  @city= City.find_by_id(params[:city].to_i)
  @profile.city = @city
  @usr = current_user
  if @usr.profile.exists? @profile
    @usr.errors.add(:profile, "is already assigned to this user") # or something to that effect
    render :new
  else 
   @usr.profile << @profile
   redirect_to root_path
  end
end

但我现在收到此错误

But I'm getting this error now

undefined method `exists?' for nil:NilClass

CURRENT_USER返回@current_user

current_user returns the @current_user

def current_user
  @current_user ||= User.find_by_remember_token(cookies[:remember_token])
end

你能告诉我请,我究竟做错了什么?

Could you tell me please, what am I doing wrong?

推荐答案

我想写这大家谁开始,以及我和都停留在这一步。

I want to write this to all of you who are beginning as well as I am and are stuck in this step.

我要创建一个新的项目并使用它来实现我在做什么错。我想通了,我是验证我加入配置文件表中的最后一次现场,不得不

I had to create a new project and play with it to realize what I was doing wrong. I figured out that I was validating a last time field I added to the Profiles table and had

# education       :string(255)     not null

但我还没有添加它尚未形式等都推出的错误是:

but I had not added it yet to the form so the error launched is:

Failed to save the new associated so_profile.

现在,你知道如果你得到这个错误,请检查您的模式,并寻找NOT_NULL字段,你可能会丢失的形式,也可以注释掉所有的模型验证,它的工作uncomment'em后确定。

Now, you know if you got this error, go check your schema and look for NOT_NULL fields you might be missing in the form, also you can comment out all your model validations and after it's working uncomment'em to be sure.

所以,我的最终模型:

class User < ActiveRecord::Base
  has_one :profile
  has_one :city, through: :profile
  attr_accessible :email, :name
end

class Profile < ActiveRecord::Base
  belongs_to :user
  belongs_to :city
  attr_accessible :age, :fcolor, :gender
end

class City < ActiveRecord::Base
  has_many :profiles
  has_many :users, through: :profiles
  attr_accessible :name
end

我的控制器:

class ProfilesController < ApplicationController
  def new
    @user = User.find_by_id(params[:id])
    @profile = Profile.new
  end

  def create
    @profile = Profile.new(params[:profile])
    city = City.find_by_id(params[:city])
    @profile.city = city
    @user = User.find_by_id(params[:userid])
    @user.profile = @profile
    if @user.save
      flash[:success] =  "Guardado"
      redirect_to profile_path(id: @user.id)
    end
  end

  def show
   @user = User.find(params[:id])
  end  
end

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      flash[:success] =  "Registrado!"
      redirect_to new_profile_path(id: @user.id)
    else
      flash[:error] =  "No Registrado :("
      redirect_to new
    end
  end

  def show
    @user = User.find_by_id(params[:id])
  end
end

在您需要使用Cookie或别的东西,以保持会话活着,一个真正的应用程序因此user_token从那里你得到的USER_ID,但它的工作原理与各协会打球。

In a real app you have to use Cookies or something else to keep the session alive and therefore the user_token from where you get the user_id, but it works to play with associations.

的意见:

配置文件/ new.html.erb

profiles/new.html.erb

<%= @user.name %>
<%= form_for @profile, url: {action: :create, userid: @user.id } do |f| %>
<%= f.label :age, "Edad" %>
<%= f.text_field :age%> <br />

<%= label :city, "Ciudad"%>
<%= select_tag :city, options_from_collection_for_select(City.all, 'id', 'name')%>

<%= f.submit %>
<% end %>

配置文件/ show.html.erb

profiles/show.html.erb

Hello <%= @user.name %><br />
Tu edad es: <%= @user.profile.age %><br />
Vives en <%= @user.profile.city.name%>

用户/ new.html.erb

users/new.html.erb

<%= form_for @user do |f|%>
<%= f.label :name, "Nombre"%>
<%= f.text_field :name, size: 20, placeholder: "Escribe tu nombre aqui" %><br />

<%= f.label :email, "Email"%>
<%= f.text_field :email, size: 20, placeholder: "Escribe tu email aqui" %><br />

<%= f.submit "Sign me up!"%>

   

用户/ show.html.erb

users/show.html.erb

Name: <%= @user.name %><br />
Email: <%= @user.email %>

这就是它!

干杯。

这篇关于如何保存到数据库在轨质量保护协会assigment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆