![](/img/trans.png)
[英]Rails - alias_method_chain with a 'attribute=' method
[英]Rails 3: alias_method_chain to set specific attribute first
当用户创建帖子时,我想先设置 user_id 属性。 我正在尝试在 arrtibutes 方法上使用 alias_method_chain 来做到这一点。 但我不确定这是否正确,因为我认为可以解决的问题仍在发生。 这个对吗?
编辑:
当我的用户创建帖子时,他们使用名为“artist_tokens”的虚拟属性将“艺术家”分配给每个帖子。 我将关系存储在艺术家 model 和一个名为 artisanships 的艺术家 ID 和 post_id 的连接表中。
我还想存储创建属于他们帖子的艺术家的用户 ID(我希望它在艺术家 model 本身内),所以我在艺术家 model 上有一个 user_id 列。
问题是当我为每个帖子创建艺术家并尝试插入帖子创建者的 user_id 时,user_id 一直显示为 NULL。 这很可能是因为帖子的 user_id 属性尚未设置。
我想解决这个问题,我需要先设置帖子的 user_id 属性,然后让属性的 rest 正常设置。 这是我找到 alias_method_chain 的地方。
attr_reader :artist_tokens
def artist_tokens=(ids)
ids.gsub!(/CREATE_(.+?)_END/) do
Artist.create!(:name => $1, :user_id => self.user_id).id
end
self.artist_ids = ids.split(",")
end
def attributes_with_user_id_first=(attributes = {})
if attributes.include?(:user_id)
self.user_id = attributes.delete(:user_id)
end
self.attributes_without_user_id_first = attributes
end
alias_method_chain :attributes=, :user_id_first
编辑:
class ArtistsController < ApplicationController
def index
@artists = Artist.where("name like ?", "%#{params[:q]}%")
results = @artists.map(&:attributes)
results << {:name => "Add: #{params[:q]}", :id => "CREATE_#{params[:q]}_END"}
respond_to do |format|
format.html
format.json { render :json => results }
end
end
在您的 controller 中,为什么不这样做:
def create
@post = Post.new :user_id => params[:post][:user_id]
@post.update_attributes params[:post]
...
end
但在我看来,在您对帖子进行验证之后创建艺术家记录会比您第一次分配属性时要好得多。
编辑
我会将其更改为这样的回调:
class Post < ActiveRecord::Base
attr_accessor :author_tokens
def artist_tokens=(tokens)
@artist_tokens = tokens.split(',')
end
after_save :create_artists
def create_artists
@artist_tokens.each do |token|
...
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.