我是Ruby on Rails的新手。我试图解决一个相当简单的问题。
在我的应用程序中,我有User,Micropost和Response模型。
用户有许多微博,并有很多回复。 Micropost有很多回复 响应属于User和Micropost。
足够简单。
在我的应用中,我将当前用户定义为current_user。
以下是我的相关路线。
resources :users
resources :microposts do
resources :responses
end
这是微博“show”视图中的一个表格,即对微博的响应。
<%= form_for([@micropost, @response]) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "Do you have an answer?", :style => "height:75px;" %>
</div>
<%= f.submit "Answer this question", class: "btn btn-primary" %>
<% end %>
这是响应控制器中的create方法
def create
@micropost = Micropost.find(params[:micropost_id])
@response = @micorpost.responses.build(response_params)
respond_to do |format|
if @response.save
format.html { redirect_to root_url, notice: 'Response was successfully created.' }
format.json { render :show, status: :created, location: @response }
else
format.html { render :new }
format.json { render json: @response.errors, status: :unprocessable_entity }
end
end
end
问题是这个 -
如何将用户ID添加到此create方法中?
有没有办法在构建方法中链接两个对象....
之类的东西 @micropost = Micropost.find(params[:micropost_id])
@response = current_user.microposts.responses.build(response_params)
这显然不起作用。
我正在尝试学习正确的方法 - 使用关系定义来实现这一点,并且考虑到目前为止Rails的一般非常棒,我相信这有一个非常简单的答案 - 当你有很多答案时只有两个相关的模型,但我似乎无法找到一个解决这种情况的地方,你有3个。
(我也在脚手架中创建了响应控制器,你可以看到这对初学者来说可能不是一个好方法)
非常感谢
答案 0 :(得分:1)
我不知道有任何方法可以使用build
一次性创建一个具有两个关联的对象。
由于您已经在使用build
和save
而不是创建,因此最简单的方法可能是设置响应&#39;用户明确地说:
@response = Micropost.find(params[:micropost_id]).responses.build(response_params)
@response.user = current_user
if @response.save …
它不聪明,但显而易见,可读。
答案 1 :(得分:0)
只需这样做
response_params = response_params.merge({user_id: current_user.id, micropost_id: params[:micropost_id]}
Response.create(respone_params))