在创建模型的新对象时设置默认值

时间:2013-06-07 00:34:39

标签: ruby-on-rails ruby

我正在学习Rails,我只是想知道我写的一些代码是否正确和安全。我有两个模型,一个用户和一个帖子模型。帖子属于用户,因此我想在创建对象时自动传递user_id。我在post控制器中使用了assign_attributes方法,使用devise提供的current_user帮助器来设置user_id。以下是我的相关代码。我想再次知道这是否正确或是否有更好的方法。

def create
@post = Post.new(params[:post])
@post.assign_attributes({:user_id => current_user.id})

end

发布模型

class Post < ActiveRecord::Base

attr_accessible :content, :title, :user_id

validates :content, :title, :presence => true

belongs_to :user

end

用户模型

class User < ActiveRecord::Base

devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me


has_many :posts

end

3 个答案:

答案 0 :(得分:2)

你非常接近。由于您已经1)被Devise提供了current_user便利助手,并且2)已将UserPost配置为has_many / belongs_to关系,因此有意义的是创建新帖子,然后将其附加到current_user。然后,在您的Post模型中,您需要分解各个属性的验证 - 您按顺序列出:content, :title的方式将无效。

# app/controllers/posts_controller.rb
def create
    post = Post.create(params[:post])
    current_user.posts << post
end

# app/models/post.rb
class Post < ActiveRecord::Base

    attr_accessible :content, :title, :user_id

    validates :content, :presence => true
    validates :title, :presence => true

    belongs_to :user
end

答案 1 :(得分:0)

我认为没有必要,因为您已经创建了帖子和用户之间的关系。如果将帖子资源嵌套到用户中,它将自动创建2个模型之间的关系。

在routes.rb

resources :users do
  resources :posts
end

完成后,您现在将帖子引用为@ user.post。我已在this question中展示了一个示例。

答案 2 :(得分:0)

我会这样说:

def create
    params[:post][:user_id] = current_user.id
    @post = Post.new(params[:post])
    @post.save
end

def create
  @post = Post.new(params[:post])
  @post.user = current_user
  if @post.save
  ...
  else
  ...
  end
end

def create
  @post = @post.new(params[:post])
  @post.user_id = current_user.id
  @post.save
end

你可以把user_id放在参数中,但那不安全。 user_id不应该在'attr_accessable'中,因此它将受到mass_assignment的保护。

相关问题