Using ransack and delegate in Rails
I have used Rails to develop web project for two years, But it's the first time to use ransack, a Gem base on Object searing. This note recording my experience of using it for my current work.
Background
Five months ago, I join in a starup company in HangZhou, which provides SASS software for car dealer. our guys cooperate with each other remotely, Sometime, our developer guys would customize software for car dealer. Fuck the outsourcing. These day, we modify our software to fix the needs for a famous car industry enterprise in China.
Back for program
Rails app provide Restful API in backend. In common case, index action gets the resources, we would filter list by some condition, for example, Cars#index
gets car list according to brand name and other relationship model. If your data is huge, Object-base searing is not suitable for your case, your should consider to use Elasticsearch.
In our API, car
model hash_one qiyuan_detetion_report
,every report has a state attribute. Now, I want to cars from Car#index
, which associate detection reports state is true.
# car model
has_one :qiyuan_detection_report
...
delegate :state, to: :qiyuan_detection_report, allow_nil: true, prefix: true
Firstly, Let's get familiar with delegate in Rails. We can delegate state attribute in qiyuan_detection_report model for car model, so car.qiyuan_detection_report_state
is the same as car.qiyuan_detection_report.state
.
go ahead is about ransack, the basic usage is skiped, if your don't know what is ransack, I suggest you read it's docutment hear.
To filter true state detection_report cars
fronted-end just needs passing params[:query][:qiyuan_detection_report_state_eq] = verified
key value to Car#index
action
and backend also simple too: car_relation_object.ransack(params[:query]).result
finally is our rspec code fragment.
it "query by delegate qiyuan_detection_report state" do
auth_get :index, query: {
qiyuan_detection_report_state_eq: "verified"
}
expect(response_json.fetch(:data).count).to eq(1)
end