传递嵌套关系的参数

时间:2012-01-28 22:19:57

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

我无法传递参数 我的应用程序设置如下:

Fact belongs_to Source
Source has_many Facts

Source嵌套在路径中的User

我正在使用Facts表单来创建Source数据。所以我在Facts模型中有getter和setter方法,如下所示:

def source_name
  source.try(:name)
end

def source_name=(name)
  self.source = source.find_or_create_by_name(name) if name.present?
end

这很有用,但它没有为父User属性设置user_id。因此,会创建源,但它们与用户无关。

我在表单中有一个带有user_id的隐藏字段,但仍在设置user_id。传递和保存user_id的最简单方法是什么,以便设置嵌套关系?

以下是Source控制器的create方法:

def create
  @user = User.find(params[:user_id])
  @source = @user.source.build(params[:source])
...
end

2 个答案:

答案 0 :(得分:0)

如果您的用户只有一个Source,请尝试以下create()方法:

def create
  @user = User.find params[:user_id]
  @user.source = Source.new params[:source]

  if @user.save
    redirect_to @user, :flash => { :success => "Source updated!" }
  else
    flash[:error] = "Failed to update the source!"
    render :action => "new"
  end
end

Source对象上创建User作为属性,然后保存User对象,应自动将SourceUser相关联。

答案 1 :(得分:0)

我认为问题在于您是直接从Fact模型中的setter方法创建源代码。除非您通过在FactController中使用类似构建的东西来建立链,否则将不会设置user_id。您在SourceController中所做的工作也需要在FactsController中完成。此外,在使用build命令时,似乎只为直接父级设置了id。您可以尝试以下内容:

def create
  @source = current_user.sources.find_or_create_by_name(params["source_name"])
  @fact = @source.facts.build(:user_id  => @source.user_id)
  ....
end

希望有所帮助。